import dayjs from "dayjs";
import path from "path";
import fs from "fs";
import {createTask} from "../../urlsniffer";

const router = require('koa-router')();

console.log('ChromeExecutablePath', process.env.ChromeExecutablePath);

router.get('/submit', async (ctx) => {
  let workerData = {
    url: ctx.request.query.url,
    ...ctx.request.query,
  }
  let taskId = await createTask(workerData);
  
  ctx.body = {ReturnCode: 200, ReturnMessage: '提交任务成功', workerData, taskId}
})

router.get('/taskList', async (ctx) => {
  
  try {
    let taskList = [];
    let staticPath = fs.readdirSync(path.join(__dirname, '../../../static/result'));
    staticPath.forEach((item, index) => {
      let taskId = item;
      let createdDate = dayjs(parseInt(taskId)).format('YYYY-MM-DD HH:mm:ss.SSS')
      taskList.push({taskId, createdDate});
    })
    taskList.sort((a, b) => {
      return b.taskId - a.taskId;
    });
    ctx.body = {ReturnCode: 200, ReturnMessage: '读取成功', taskList}
  } catch (e) {
    ctx.body = {ReturnCode: 400, ReturnMessage: '读取失败', error: e}
  }
  
})


function getDomList(node, set) {
  if (Array.isArray(node)) {
    for (let item of node) {
      getDomList(item, set);
    }
  } else {
    if (Array.isArray(node.result)) {
      getDomList(node.result, set);
    } else {
      let url = node.result;
      if (url.startsWith('http')) {
        let origin = new URL(url).origin
        set.add(origin);
      }
    }
  }
}

router.get('/taskDetail', async (ctx) => {
  let taskId = ctx.request.query.taskId;
  let exists = fs.existsSync(path.join(__dirname, `../../../static/result/${taskId}/result.json`));
  let domainList = [];
  let detail = [];
  if (exists) {
    let domainSet = new Set();
    detail = require(`../../../static/result/${taskId}/result.json`);
    getDomList(detail, domainSet);
    domainSet.forEach((value => {
      domainList.push(value);
    }))
    console.log(domainList);
  }
  ctx.body = {
    ReturnCode: 200,
    ReturnMessage: '读取成功',
    status: exists ? '已完成' : '未完成',
    domainList,
    detail
  }
})

export default router;